﻿// <copyright file="Form1.cs" company="None">(c) Guy Smith-Ferrier, 2012</copyright>

namespace AcceptLanguageSetterTrayApplication
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Text;
    using System.Windows.Forms;
    using Browser;

    /// <summary>
    /// Form1 is the AcceptLanguageSetterTrayApplication main form
    /// </summary>
    public partial class Form1 : Form
    {
        /// <summary>
        /// Gets or sets the IBrowserLanguagePreference
        /// </summary>
        private IBrowserLanguagePreference browserLanguagePreference;

        /// <summary>
        /// Initializes a new instance of the Form1 class
        /// </summary>
        public Form1()
        {
            this.InitializeComponent();
            WindowState = FormWindowState.Minimized;

            this.internetExplorerToolStripMenuItem.Enabled = new IEBrowserLanguagePreference().BrowserExists;
            this.firefoxToolStripMenuItem.Enabled = new FirefoxBrowserLanguagePreference().BrowserExists;
            this.chromeToolStripMenuItem.Enabled = new ChromeBrowserLanguagePreference().BrowserExists;

            string defaultBrowserCommand = DefaultBrowser.Command;
            if (this.internetExplorerToolStripMenuItem.Enabled && defaultBrowserCommand.IndexOf("iexplore.exe", 0, StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                this.internetExplorerToolStripMenuItem_Click(null, null);
            }
            else if (this.firefoxToolStripMenuItem.Enabled && defaultBrowserCommand.IndexOf("firefox.exe", 0, StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                this.firefoxToolStripMenuItem_Click(null, null);
            }
            else if (this.chromeToolStripMenuItem.Enabled && defaultBrowserCommand.IndexOf("chrome.exe", 0, StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                this.chromeToolStripMenuItem_Click(null, null);
            }
        }

        /// <summary>
        /// LoadLanguagePreference loads the browser's language preference and updates the menu with the language preferences
        /// </summary>
        private void LoadLanguagePreference()
        {
            this.ClearLanguageMenuItems();

            string languages = this.browserLanguagePreference.LanguagePreferences;
            int menuItemIndex = 1;
            foreach (string language in languages.Split(','))
            {
                string cultureName = language.Split(';')[0];
                ToolStripItem toolStripItem = new ToolStripMenuItem(string.Format("{0} ({1})", cultureName, this.GetCultureDisplayName(cultureName)));
                toolStripItem.Tag = language;
                toolStripItem.Click += new EventHandler(this.languageToolStripMenuItem_Click);
                this.contextMenuStrip.Items.Insert(menuItemIndex++, toolStripItem);
            }
        }

        /// <summary>
        /// The event handler for the Language menu item's Click event
        /// </summary>
        /// <param name="sender">The object that sent the event</param>
        /// <param name="e">The EventArgs</param>
        [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "This is autogenerated by Visual Studio")]
        private void languageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem toolStripMenuItem = (ToolStripMenuItem)sender;
            string language = toolStripMenuItem.Tag.ToString();

            // move this menu item's language to the top of the list (and remove any weighting from it now that it is the top item)
            StringBuilder builder = new StringBuilder(language.Split(';')[0]);
            foreach (ToolStripItem toolStripItem in this.contextMenuStrip.Items)
            {
                if (toolStripItem != this.exitToolStripMenuItem && toolStripItem != this.browserToolStripMenuItem && toolStripItem != toolStripMenuItem)
                {
                    language = toolStripItem.Tag.ToString();
                    builder.Append("," + language);
                }
            }

            this.browserLanguagePreference.LanguagePreferences = builder.ToString();
        }

        /// <summary>
        /// Gets the DisplayName of the given culture if it is valid otherwise it gets "Unknown"
        /// </summary>
        /// <param name="cultureName">The name of the culture</param>
        /// <returns>The DisplayName of the given culture if it is valid otherwise it gets "Unknown"</returns>
        private string GetCultureDisplayName(string cultureName)
        {
            try
            {
                CultureInfo cultureInfo = new CultureInfo(cultureName);
                return cultureInfo.DisplayName;
            }
            catch
            {
                return "Unknown";
            }
        }

        /// <summary>
        /// ClearLanguageMenuItems removes all of the menu items that are for a language
        /// </summary>
        private void ClearLanguageMenuItems()
        {
            List<ToolStripItem> toolStripItems = new List<ToolStripItem>();
            foreach (ToolStripItem toolStripItem in this.contextMenuStrip.Items)
            {
                toolStripItems.Add(toolStripItem);
            }

            foreach (ToolStripItem toolStripItem in toolStripItems)
            {
                if (toolStripItem != this.exitToolStripMenuItem && toolStripItem != this.browserToolStripMenuItem)
                {
                    this.contextMenuStrip.Items.Remove(toolStripItem);
                }
            }
        }

        /// <summary>
        /// The event handler for the NotifyIcon's Double Click event
        /// </summary>
        /// <param name="sender">The object that sent the event</param>
        /// <param name="e">The EventArgs</param>
        [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "This is autogenerated by Visual Studio")]
        private void notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            this.ShowInTaskbar = true;
        }

        /// <summary>
        /// The event handler for the ContextMenuStrip's Opening event
        /// </summary>
        /// <param name="sender">The object that sent the event</param>
        /// <param name="e">The EventArgs</param>
        [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "This is autogenerated by Visual Studio")]
        private void contextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            this.LoadLanguagePreference();
        }

        /// <summary>
        /// The event handler for the Exit menu item's click event
        /// </summary>
        /// <param name="sender">The object that sent the event</param>
        /// <param name="e">The EventArgs</param>
        [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "This is autogenerated by Visual Studio")]
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// The event handler for the Internet Explorer menu item's click event
        /// </summary>
        /// <param name="sender">The object that sent the event</param>
        /// <param name="e">The EventArgs</param>
        [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "This is autogenerated by Visual Studio")]
        private void internetExplorerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.internetExplorerToolStripMenuItem.Checked = true;
            this.firefoxToolStripMenuItem.Checked = false;
            this.chromeToolStripMenuItem.Checked = false;
            this.browserLanguagePreference = new IEBrowserLanguagePreference();
        }

        /// <summary>
        /// The event handler for the Firefox menu item's click event
        /// </summary>
        /// <param name="sender">The object that sent the event</param>
        /// <param name="e">The EventArgs</param>
        [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "This is autogenerated by Visual Studio")]
        private void firefoxToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.internetExplorerToolStripMenuItem.Checked = false;
            this.firefoxToolStripMenuItem.Checked = true;
            this.chromeToolStripMenuItem.Checked = false;
            this.browserLanguagePreference = new FirefoxBrowserLanguagePreference();
        }

        /// <summary>
        /// The event handler for the Chrome menu item's click event
        /// </summary>
        /// <param name="sender">The object that sent the event</param>
        /// <param name="e">The EventArgs</param>
        [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "This is autogenerated by Visual Studio")]
        private void chromeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.internetExplorerToolStripMenuItem.Checked = false;
            this.firefoxToolStripMenuItem.Checked = false;
            this.chromeToolStripMenuItem.Checked = true;
            this.browserLanguagePreference = new ChromeBrowserLanguagePreference();
        }
    }
}
